from Selenium2Library.keywords.keywordgroup import KeywordGroup
import httplib
from xml.etree import ElementTree
import hashlib
import base64

class _WebServiceKeywords(KeywordGroup):
    """Library for WebService Keywords purposes.
    
    This library is used in Breeze projects.
    """
    def __init__(self):
        """Does nothing. init only"""
        print '_WebServiceKeywords.__init__'  
        self.conn = None
        
    def connect_to_server(self, url, port):  
        if url.split(":")[0]=="http":
            self.conn = httplib.HTTPConnection(url.split("//")[1], int(port))
        elif url.split(":")[0]=="https":
            self.conn = httplib.HTTPSConnection(url.split("//")[1], int(port))
        else:
            pass

    def close_connection(self):
        self.conn.close()
        self.conn = None
        
    def send_request(self, path, params, POST="POST"):
        self.conn.request(POST, path, body=params)

        result = self.conn.getresponse()
        resultStatus = result.status
        resultContent = result.read()
        self._info(resultContent)

        return resultContent

    def check_assertion(self, response, errorCode):
        if (errorCode in response):         
            return True    
        else:
            raise AssertionError("Could not find the expected string '%s' in response." % (errorCode))
        
    def POST(self, path='/bsoi/services/startrek', body=None):
        body = body or '''
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:end="http://endpoint.startrek.bsoi.scb.com/">
               <soapenv:Header>
                            <digest>NkSY+yvIRybyIxemitWxvfSG9hc=</digest>
               </soapenv:Header>
               <soapenv:Body>
                  <end:makeCashIn>
                     <cashInRequest>
                        <requestHeader>
                           <clientContext>
                              <channel>IBKWL</channel>
                              <country>SG</country>
                           </clientContext>
                           <serviceContext>
                              <requestId></requestId>
                           </serviceContext>
                           <userContext>
                              <language>en</language>
                              <userId>sitcb024Q</userId>
                           </userContext>
                        </requestHeader>
                        <cashInVO>
                           <amount>100</amount>
                           <currencyCode>SGD</currencyCode>
                           <remark>makeCashin</remark>
                           <transferDate></transferDate>
                        </cashInVO>
                     </cashInRequest>
                  </end:makeCashIn>
               </soapenv:Body>
            </soapenv:Envelope>'''
        self.conn.request("POST", path, body=body)
        return self.conn.getresponse().read()
        
    def sha1_base64_digest(self, plaintext='IBKWL'+'SG'+''+'en'+'sitcb024Q'+'100'+'SGD' +'makeCashin'+''):
        """ digest  = base64( sha1( channel + country + requestId + language + userId + amount + currencyCode + remark + transferDate))
        """
       
        sh = hashlib.sha1(plaintext).digest()
        ba = base64.b64encode(sh)
        return ba
        
